import 'dart:ui';

import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'components/danmaku_comment_widget.dart';
import 'map_wall_page.dart';
import 'ranking_page.dart';
import 'search_page.dart';
import 'video_player_page.dart';
import '../../core/widgets/report_dialog.dart';
import '../../core/utils/notification_utils.dart';

/// 官方推荐数据模型
class OfficialRecommendation {
  final String id;
  final String title;
  final String description;
  final String imageUrl;
  final String videoUrl;

  const OfficialRecommendation({
    required this.id,
    required this.title,
    required this.description,
    required this.imageUrl,
    required this.videoUrl,
  });
}

/// 首页界面
class VamosHomeInterface extends StatefulWidget {
  const VamosHomeInterface({super.key});

  @override
  State<VamosHomeInterface> createState() => _VamosHomeInterfaceState();
}

class _VamosHomeInterfaceState extends State<VamosHomeInterface> {
  // 官方推荐数据
  List<OfficialRecommendation> _recommendations = [
    const OfficialRecommendation(
      id: '1',
      title: '15 Super Cool 3D-Printed Items',
      description:
          'Get ready to be amazed by these 15 most awesome 3D-printed creations! Ranging from exquisite little gadgets to breathtaking designs, these printed works push creativity to the absolute limit...',
      imageUrl: 'assets/images/recommend1.png',
      videoUrl:
          'https://d3197c2qdpub41.cloudfront.net/com.vamos.ios/bfea98ef0117c15108c883da442cb83a.mp4',
    ),
    const OfficialRecommendation(
      id: '2',
      title: 'How to Connect 3D-Printed Parts! ',
      description:
          'How to Join 3D-Printed Components Together? Let’s Figure It Out!',
      imageUrl: 'assets/images/recommend2.png',
      videoUrl:
          'https://d3197c2qdpub41.cloudfront.net/com.vamos.ios/31f4c4837bfcab1127fa1c733b142c1e.mp4',
    ),
    const OfficialRecommendation(
      id: '3',
      title: 'I Tried 3D Printing as a Beginner: Is It Worth It?!',
      description:
          'I Tried 3D Printing, and I Want to Answer Some Important Questions We All Care About: Is It Worth It? Can It Make Life Better? Should You Try It with Me?',
      imageUrl: 'assets/images/recommend3.png',
      videoUrl:
          'https://d3197c2qdpub41.cloudfront.net/com.vamos.ios/24261a1d14b426603b32fdb77da63ae6.mp4',
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: [
            SizedBox(height: MediaQuery.of(context).padding.top),

            _buildTitleSection(),

            _buildSearchSection(),

            Expanded(child: _buildScrollableContent()),
          ],
        ),
      ),
    );
  }

  /// 构建标题区域
  Widget _buildTitleSection() {
    return Container(
      width: double.infinity,
      alignment: Alignment.center,
      child: Text(
        'Vamos',
        style: TextStyle(
          color: Colors.white,
          fontSize: 16.sp,
          fontFamily:
              GoogleFonts.goblinOne(fontWeight: FontWeight.w400).fontFamily,
          fontWeight: FontWeight.bold,
        ),
      ).paddingTop(0.h).paddingBottom(20.h),
    );
  }

  /// 构建搜索区域
  Widget _buildSearchSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      height: 50.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: const Color(0x51D9D9D9),
        borderRadius: BorderRadius.circular(25.r),
      ),
      child: Row(
        children: [
          SizedBox(width: 16.w),

          Expanded(
            child:
                Text(
                  'Search for content...',
                  style: TextStyle(color: Colors.white, fontSize: 16.sp),
                ).center(),
          ),

          Image.asset(
            'assets/images/search.png',
            width: 32.w,
            height: 32.w,
          ).paddingRight(10.w),
        ],
      ).inkWell(
        onTap: () {
          Navigator.push(
            context,
            PageRouteBuilder(
              pageBuilder:
                  (context, animation, secondaryAnimation) =>
                      VamosSearchInterface(),
              transitionsBuilder: (
                context,
                animation,
                secondaryAnimation,
                child,
              ) {
                return FadeTransition(opacity: animation, child: child);
              },
              transitionDuration: Duration(milliseconds: 200),
            ),
          );
        },
      ),
    ).paddingBottom(16.h);
  }

  /// 构建可滚动内容
  Widget _buildScrollableContent() {
    return SingleChildScrollView(
      child: Column(
        children: [
          // Map Wall 图片按钮
          _buildMapWallSection(context),

          // 排行榜弹幕区域
          _buildLeaderboardSection(),

          // 官方推荐区域
          _buildRecommendationsSection(),

          // 底部间距
          SizedBox(height: 120.h),
        ],
      ),
    );
  }

  /// 构建Map Wall区域
  Widget _buildMapWallSection(BuildContext context) {
    return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(
              'assets/images/map_wall.png',
              width: double.infinity,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  width: double.infinity,
                  height: 150.h,
                  decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.map, size: 40.sp, color: Colors.grey[600]),
                      SizedBox(height: 8.h),
                      Text(
                        'Map Wall',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
        )
        .inkWell(
          onTap: () {
            Navigator.of(context).push(
              TransitionPageRoute(
                builder: (context) => VamosMapWallInterface(),
                transitionAnimation: DirectionalPixelatedTransition(
                  duration: const Duration(milliseconds: 600),
                  colors: [
                    Color(0xFF83BE4A),
                    Color(0xFFF3E3C6),
                    Color(0xFFFB894E),
                  ],
                ),
              ),
            );
          },
        )
        .paddingBottom(20.h);
  }

  /// 构建排行榜弹幕区域
  Widget _buildLeaderboardSection() {
    return Container(
      height: 300.h,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Stack(
        children: [
          Positioned(
            bottom: 0.h,
            left: 0,
            right: 0,
            child: _buildDanmakuLayer(),
          ),
          _buildLeaderboardBackground(),
        ],
      ),
    ).inkWell(
      onTap: () {
        Navigator.of(context).push(
          TransitionPageRoute(
            builder: (context) => VamosRankingInterface(),
            transitionAnimation: BrushStrokeTransition(
              direction: TransitionDirection.left,
              colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
            ),
          ),
        );
      },
    );
  }

  /// 构建排行榜背景
  Widget _buildLeaderboardBackground() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12.r),
      child: Image.asset(
        'assets/images/leaderboard.png',
        width: double.infinity,
        fit: BoxFit.fitWidth,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            width: double.infinity,
            height: 200.h,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.purple.withOpacity(0.8),
                  Colors.blue.withOpacity(0.8),
                ],
              ),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.leaderboard, size: 40.sp, color: Colors.white),
                SizedBox(height: 8.h),
                Text(
                  'Leaderboard',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 构建弹幕层
  Widget _buildDanmakuLayer() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(24.r),
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 50, sigmaY: 50),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(24.r),
            border: Border.all(color: Colors.white.withOpacity(0.2)),
          ),
          width: double.infinity,
          height: 170.h,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              // 第一排弹幕
              DanmakuCommentWidget(height: 30.h, rowIndex: 0),

              // 排间间距
              SizedBox(height: 10.h),

              // 第二排弹幕
              DanmakuCommentWidget(height: 30.h, rowIndex: 1),

              // 排间间距
              SizedBox(height: 10.h),

              // 第三排弹幕
              DanmakuCommentWidget(height: 30.h, rowIndex: 2),
              SizedBox(height: 10.h),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建官方推荐区域
  Widget _buildRecommendationsSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text('You May Also Like')
              .fontSize(16.sp)
              .textColor(Colors.white)
              .fontFamily(
                GoogleFonts.goblinOne(fontWeight: FontWeight.w400).fontFamily!,
              )
              .paddingBottom(12.h)
              .paddingTop(18.h),

          // 横向滚动列表
          SizedBox(
            height: 300.h,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _recommendations.length,
              itemBuilder: (context, index) {
                return _buildRecommendationItem(_recommendations[index]);
              },
            ),
          ),
        ],
      ),
    ).paddingBottom(20.h);
  }

  /// 构建单个推荐项
  Widget _buildRecommendationItem(OfficialRecommendation recommendation) {
    return Container(
      width: 245.w,
      margin: EdgeInsets.only(right: 12.w),
      decoration: ShapeDecoration(
        color: Colors.white.withValues(alpha: 0.10),
        shape: RoundedRectangleBorder(
          side: BorderSide(width: 1.w, color: const Color(0x7F404040)),
          borderRadius: BorderRadius.circular(20.r),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图片区域
          AspectRatio(
            aspectRatio: 245 / 191,
            child: Stack(
              children: [
                // 主图片
                ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child: Image.asset(
                    recommendation.imageUrl,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        decoration: BoxDecoration(
                          color: Colors.grey[300],
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child:
                            Icon(
                              Icons.image,
                              size: 40.sp,
                              color: Colors.grey[600],
                            ).center(),
                      );
                    },
                  ),
                ),

                // 左上角举报按钮
                Positioned(
                  top: 0.h,
                  left: 0.w,
                  child: Container(
                    width: 70.w,
                    height: 30.w,
                    decoration: BoxDecoration(
                      color: const Color(0xFFF7CEBA),
                      borderRadius: BorderRadius.circular(10.r),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/report3.png',
                          width: 12.w,
                          height: 12.w,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          'Report',
                          style: TextStyle(
                            color: Colors.black,
                            fontFamily:
                                GoogleFonts.poppins(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily,
                            fontSize: 10.sp,
                          ),
                        ),
                      ],
                    ),
                  ).inkWell(
                    onTap: () {
                      _handleRecommendationReport(recommendation);
                    },
                  ),
                ),

                // 右下角前往按钮
                Positioned(
                  bottom: 0.h,
                  right: 0.w,
                  child: Container(
                    width: 46.w,
                    height: 46.w,
                    decoration: ShapeDecoration(
                      color: const Color(0xFFCEF672),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.r),
                      ),
                    ),
                    child:
                        Image.asset(
                          'assets/images/arrow.png',
                          width: 26.w,
                          height: 26.w,
                        ).center(),
                  ),
                ),
              ],
            ),
          ),

          Spacer(),
          // 标题
          Text(
            recommendation.title,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
              fontFamily:
                  GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ).paddingHorizontal(13.w),

          SizedBox(height: 8.h),

          // 描述
          Text(
            recommendation.description,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.white.withOpacity(0.7),
              fontFamily:
                  GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ).paddingHorizontal(13.w),
          Spacer(),
        ],
      ),
    ).inkWell(
      onTap: () {
        _navigateToVideoPlayer(recommendation);
      },
    );
  }

  /// 处理推荐项举报
  void _handleRecommendationReport(OfficialRecommendation recommendation) {
    showVamosReportDialog(
      context: context,
      title: 'Report Recommendation',
      subtitle: 'Please select a reason for reporting this recommendation.',
      onReportSubmitted: (VamosReportOption option) {
        _deleteRecommendation(recommendation);
      },
    );
  }

  /// 删除推荐项
  void _deleteRecommendation(OfficialRecommendation recommendation) {
    setState(() {
      _recommendations.removeWhere((item) => item.id == recommendation.id);
    });
    NotificationUtils.showSuccess(
      context,
      message: 'You won\'t see this again.',
    );
  }

  /// 跳转到视频播放页面
  void _navigateToVideoPlayer(OfficialRecommendation recommendation) {
    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => VamosVideoPlayerInterface(
              videoUrl: recommendation.videoUrl,
              title: recommendation.title,
              description: recommendation.description,
            ),
        transitionAnimation: BrushStrokeTransition(
          direction: TransitionDirection.right,
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }
}
